package com.rao.mongodb.explorer.dao;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
import com.rao.mongodb.explorer.common.config.DepotMongoConfig;
import com.rao.mongodb.explorer.entity.OFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.stereotype.Repository;

/**
 * 存储仓库持久层实现类
 *
 * @author raos
 * @emil 991207823@qq.com
 * @date 2021/8/31 21:46
 */
@Repository
public class DepotRepository {

    @Autowired
    @Qualifier(DepotMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate mongoTemplate;

    /**
     *
     * @param file
     * @return
     */
    public String putFile(OFile file) {
        return putFile(file, null);
    }

    /**
     *
     * @param file
     * @param alias
     * @return
     */
    public String putFile(OFile file, String alias) {
        try {
            String id = file.getId();
            if (exists(id)) {
                return id;
            }
            String fileName = file.getName();
            GridFSInputFile gfs = getGridFS().createFile(file);
            gfs.put("aliases", alias);
            gfs.put("filename", fileName);
            gfs.put("contentType", fileName.substring(fileName.lastIndexOf(".")));
            gfs.save();
            return id;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("存储文件时发生错误！！！");
        }
        return null;
    }

    /**
     * 判断文件是否存在
     * @param id 文件标识
     * @return
     */
    public boolean exists(String id) {
        DBObject query = new BasicDBObject("md5", id);
        GridFSDBFile dbfile = getGridFS().findOne(query);
        return dbfile != null;
    }

    // 取出文件
//    public InputStream getFile(String id) {
//        try {
//            DBObject query = new BasicDBObject("md5",id);
//            GridFSDBFile dbfile = getGridFS().findOne(query);
//            if (dbfile != null) {
//                return dbfile.getInputStream();
//            }
//        } catch (Exception e) {
//            // TODO: handle exception
//        }
//        return null;
//    }

    private GridFS getGridFS() {
        DB db = mongoTemplate.getMongoDbFactory().getLegacyDb();
        // 获取fs的根节点
        return new GridFS(db, getCollectionName());
    }

    private String getCollectionName() {
        return OFile.class.getAnnotation(Document.class).collection();
    }

}
